package pdf.utils;

import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author v-sunms.gd@chinatelecom.cn
 * @date 2021-11-16 9:49
 *
 * 生成指定内容的二维码
 *
 */
public class CodeUtil {

    public static BufferedImage generateQrCode(String content) {
        return QrCodeUtil.generate(
                content,
                QrConfig.create()
                        .setErrorCorrection(ErrorCorrectionLevel.H)
                        .setWidth(100)
                        .setHeight(100)
                        .setMargin(-1));
    }

    /**
     * 设置二维码图片背景透明
     * @date
     * @param srcImage
     * @param alpha
     * @return
     * @throws IOException
     */
    public static BufferedImage transparentImage(BufferedImage srcImage,
                                                 int alpha) throws IOException {
        int imgHeight = srcImage.getHeight();//取得图片的长和宽
        int imgWidth = srcImage.getWidth();
        int c = srcImage.getRGB(3, 3);
        //防止越位
        if (alpha < 0) {
            alpha = 0;
        } else if (alpha > 10) {
            alpha = 10;
        }
        BufferedImage tmpImg = new BufferedImage(imgWidth, imgHeight,BufferedImage.TYPE_4BYTE_ABGR);//新建一个类型支持透明的BufferedImage
        for(int i = 0; i < imgWidth; ++i)//把原图片的内容复制到新的图片，同时把背景设为透明
        {
            for(int j = 0; j < imgHeight; ++j){
                //把背景设为透明
                if(srcImage.getRGB(i, j) == c){
                    tmpImg .setRGB(i, j, c & 0x00ffffff);
                }
                //设置透明度
                else{
                    int rgb = tmpImg .getRGB(i, j);
                    rgb = ((alpha * 255 / 10) << 24) | (rgb & 0x00ffffff);
                    tmpImg .setRGB(i, j, rgb);
                }
            }
        }
        return tmpImg ;
    }

    /**
     * 将BufferedImage转换为InputStream
     * @param image
     */
    public static InputStream bufferedImageToInputStream(BufferedImage image){
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            ImageIO.write(image, "png", os);
            return new ByteArrayInputStream(os.toByteArray());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static byte[] readInputStream(InputStream inStream) throws IOException {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[10240];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        inStream.close();
        return outStream.toByteArray();

    }

}
